package com.weibo.util;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;

import javax.servlet.http.*;

import org.hibernate.*;
import com.weibo.domain.BasicInfo;
import com.weibo.hibernate.MySessionFactory;

public class StaticUtil
{
	static public String getIdByReq(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String loginId = null;
		String userId = null;
		String userPwd = null;

		HttpSession session = request.getSession(false);
		if (session != null)
		{
			userId = (String) session.getAttribute("userId");
			if (userId != null)
				return userId;
		}

		loginId = null;
		userId = null;
		Cookie[] cookie = request.getCookies();
		if (cookie != null)
		{
			for (int i = 0; i < cookie.length; i++)
			{
				if (cookie[i].getName().equals("loginId"))
				{
					loginId = cookie[i].getValue();
					break;
				}
			}

			if (loginId != null)
			{
				userId = getUserIdByLoginId(loginId);
				if (userId != null)
				{
					request.getSession().setAttribute("userId", userId);
					return userId;
				}
			}
		}

		userId = request.getParameter("userId");
		userPwd = request.getParameter("userPwd");
		if ((userPwd != null) && (userId != null))
		{
			loginId = checkUser(userId, userPwd);
			if (loginId != null)
			{
				request.getSession().setAttribute("userId", userId);
				
				Cookie c1 = new Cookie("loginId", loginId);//大家打开自己电脑上C:\Windows\System32\drivers\etc文件
															//夹下的host文件，增加一行127.0.0.1 swb.com并回车保存，以便
															//通过 http://swb.vicp.net:8080/ShabbyWeibo访问本地服务器
				c1.setPath("/");
				c1.setDomain(".swb.com");
				c1.setMaxAge(60 * 60 * 24);
				
				Cookie c2=new Cookie("loginId", loginId);//默认指向我402寝室的路由，路由转发到我的电脑
												//所以如果我电脑在寝室开着，且打开Tomcat则大家能访问域名 http://tjswb.vicp.net:8080/ShabbyWeibo
				c2.setPath("/");
				c2.setDomain(".tjswb.vicp.net");
				c2.setMaxAge(60 * 60 * 24);
				response.addCookie(c2);
				
				return userId;
			}
		}

		return null;
	}

	static public String getUserIdByLoginId(String loginId)
	{
		Session hs = MySessionFactory.getSession();
		String hql = new String("from BasicInfo where loginId='" + loginId
				+ "'");
		hs.beginTransaction();// 开始事务
		List<BasicInfo> list = hs.createQuery(hql).list();
		for (BasicInfo info : list)
		{
			if (info.getLoginId().equals(loginId))
			{
				hs.getTransaction().commit();
				// hs.close();
				return info.getUserId();
			}
		}

		return null;
	}

	static public String checkUser(String userId, String userPwd)// 返回loginId
	{
		Session hs = MySessionFactory.getSession();
		String hql = new String("from BasicInfo where userId='" + userId
				+ "' and userPwd='" + userPwd + "'");
		Transaction tran = hs.beginTransaction();// 开始事务
		List<BasicInfo> list = hs.createQuery(hql).list();
		if (list.isEmpty())
			return null;
		else
		{
			BasicInfo info = list.get(0);
			info.setLoginId(generateString(15));
			hs.saveOrUpdate(info);
			tran.commit();
			return info.getLoginId();
		}
	}

	public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String numberChar = "0123456789";

	public static String generateString(int length) // 参数为返回随机数的长度
	{
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < length; i++)
		{
			sb.append(allChar.charAt(random.nextInt(allChar.length())));
		}
		return sb.toString();
	}

	public static boolean ifUserExisted(String userId, String userName)
	{
		Session hs = MySessionFactory.getSession();
		String hql = new String("from BasicInfo where userId='" + userId
				+ "' or userName='" + userName + "'");
		Transaction tran = hs.beginTransaction();// 开始事务
		List<BasicInfo> list = hs.createQuery(hql).list();
		if (list.isEmpty())
			return false;
		else
			return true;
	}

	public static void clearCookieSession(HttpServletRequest request,
			HttpServletResponse response)
	{
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies)
		{
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		}
		
		request.getSession().removeAttribute("userId");
	}
}
